import React,{Component} from 'react'
import * as pub from '../../config/public';
import { Spin,message} from 'antd';
import * as fetch from '../../config/fetch';
import {Link} from 'react-router'
import Layer from '../Layer'
import $ from 'jquery'
//var test_time = 60;
class RadioList extends Component {
	constructor(args) {
		super();
		this.state = {
			single:[]
		}
	}
	componentWillReceiveProps(nextProps) {
		this.setState({
			single: nextProps.single
		}, () => {

			// $('.radio-test-online').each(function(i) {
			// 	let answer = pub.getAnswer(nextProps.single[i].answer);
			// 	$(this).find("input[type='radio']").each((index, el) => {
			// 		for (let x of answer) {
			// 			if (x === index) {
			// 				el.checked = true;
			// 			}
			// 		}
			// 	})

			// })
		})
	}
	render(){
		return(
			<div className="topic radio-topic mar-b-20">
						{
                           this.state.single.length===0?null:<h3>单项选择题：</h3>
				        }
						{this.state.single.map((item,index)=>{
							return(
						           <dl key={index} className='radio-test-online'>
						           	<dt>{index+1}、{item.title}</dt>
						           	<dd><label><input className="describeA" type="radio" name={'radio' + index}/>A. {item.A}</label></dd>
						           	<dd><label><input className="describeB" type="radio" name={'radio' + index}/>B. {item.B}</label></dd>
						           	<dd><label><input className="describeC" type="radio" name={'radio' + index}/>C. {item.C}</label></dd>
						           	<dd><label><input className="describeD" type="radio" name={'radio' + index}/>D. {item.D}</label></dd>
						           </dl>
								)
						})}

			</div>
			)
	}
}
class MultiselectList extends Component {
	constructor(args) {
		super();
		this.state = {
			multiple:[]
		}
	}
	componentWillReceiveProps(nextProps) {
		this.setState({
			multiple: nextProps.multiple
		}, () => {
			
			// $('.check-test-online').each(function(i) {
			// 	let answer = pub.getAnswer(nextProps.checkbox[i].answer);
			// 	$(this).find("input[type='checkbox']").each((index, el) => {
			// 		for (let x of answer) {
			// 			if (x === index) {
			// 				el.checked = true;
			// 			}
			// 		}
			// 	})

			// })
		})
	}
	render(){
		return(
			<div className="topic check-topic">
						{
                           this.state.multiple.length===0?null:<h3>多选选择题：</h3>
				        }
						{this.state.multiple.map((item,index)=>{
							return(
						           <dl key={index} className='check-test-online'>
						           	<dt>{index+1}、{item.title}</dt>
						           	<dd><label><input className="describeA" type="checkbox" />A. {item.A}</label></dd>
						           	<dd><label><input className="describeB" type="checkbox" />B. {item.B}</label></dd>
						           	<dd><label><input className="describeC" type="checkbox" />C. {item.C}</label></dd>
						           	<dd><label><input className="describeD" type="checkbox" />D. {item.D}</label></dd>
						           </dl>
								)
						})}

			</div>
			)
	}
}
class TestPaper extends Component {
	constructor(args) {
		super();
		this.state = {
			showTip: true,
			showLayer:false,
			loading:false,
			point:0,
			end:false,
			single:[],
			multiple:[],
			testScores:0,
			testpapers:{},
			counterAuction: 0,
            hourAuction: '00',
            minAuction: '00',
            secAuction: '00',
			answerTime:60,
			removes:true
		
		}
	}
	componentWillMount() {
		this.stopTimer();
		this.setState({
			loading: true,
		});
		fetch.getTestPaper({testpaperId:this.props.params.id}).then((data) => {
			if (data.result === 'RC100') {
				let single=[],multiple=[];
				for(let x of data.titleList){
					if(x.titleType === '1'){
						single.push(x);
					}else{
						multiple.push(x);
					}
				}
				this.setState({
					loading: false,
					single,
					multiple,
					testpapers:data.testpapers,
					answerTime:data.testpapers.answerTime?data.testpapers.answerTime:0,
				},()=>{
					this.countdown();
				});
			} else {
				this.setState({
					loading: false,
					removes:false
				})
				message.error(data.errMsg, 5);
			}

		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false,
			});
		})
	}
	componentWillUnmount(){
			this.clearTimer();
           if (this.timerAuctionHandler) {
            clearInterval(this.timerAuctionHandler)
            this.setState({
                hourAuction: '00',
                minAuction: '00',
				secAuction: '00',
            })
        }
	}
	countdown() {
        let t = parseInt(this.state.answerTime,10)*60;
        let h = parseInt(t / 3600,10);
        let m = parseInt((t - h * 3600) / 60,10);
        let s = t - h * 3600 - m * 60;

        this.setState({
            counterAuction:t,
            hourAuction: this.getNumber(h),
            minAuction: this.getNumber(m),
            secAuction: this.getNumber(s)
        });

        if (t !== 0) {
            this.startTimer()
        }
    }

	startTimer() {
        if (!this.timerAuctionHandler) {
            this.timerAuctionHandler = setInterval(() => {

                let counter = parseInt(this.state.counterAuction,10) - 1;

                if (counter === 0) {
                    this.stopTimer()
                }

                let t = parseInt(counter,10);
                let h = parseInt(t / 3600,10);
                let m = parseInt((t - h * 3600) / 60,10);
                let s = t - h * 3600 - m * 60;

                this.setState({
                    counterAuction: counter,
                    hourAuction: this.getNumber(h),
                    minAuction: this.getNumber(m),
                    secAuction: this.getNumber(s)
                })
            }, 1000);
        }
    }
	stopTimer() {
        if (this.timerAuctionHandler) {
			clearInterval(this.timerAuctionHandler)
            this.setState({
                hourAuction: '00',
                minAuction: '00',
				secAuction: '00',
				
            },()=>{
				this.submit();
			})
        }
    }
	getNumber(no) {
        let number = '00';
        if (no < 10) {
            number = '0' + no;
        } else {
            number = no + ''
        }
        return number;
    }
	// countDown() {
	// 	 this.timer = setInterval(() => {
	// 	 	if(this.state.end){
	// 	 		return;
	// 	 	}
	// 		if (test_time === 0) {
	// 			this.submit();
	// 			return;
	// 		}
	// 		test_time --;
	// 	}, 2000);
	// }
	submit() {
		let radioTitles = [];
		let checkboxTitles = [];
		clearInterval(this.timerAuctionHandler);
		$('.radio-test-online').each((i,element)=> {
			let checkboxList = $(element).find("input[type='radio']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			radioTitles.push({
				radioTitleType:'1',
				radioAnswer:answer
			})
		})
		$('.check-test-online').each((i, element)=> {
			let checkboxList = $(element).find("input[type='checkbox']");
			let answer = 0;
			checkboxList.each((index, el) => {
				if (el.checked) {
					switch (index) {
						case 0:
							answer += 1;
							break;
						case 1:
							answer += 2;
							break;
						case 2:
							answer += 4;
							break;
						case 3:
							answer += 8;
							break;
						default:
							break;
					}
				}
			})
			checkboxTitles.push({
				checkboxTitleType:'2',
				checkboxAnswer:answer
			})
		})


		let formData = new FormData();
		formData.append('radioTitles', JSON.stringify(radioTitles));
		formData.append('checkboxTitles', JSON.stringify(checkboxTitles));
		let testPapeData = {
			testpaperId: this.props.params.id
		}
		formData.append('testPapeData', JSON.stringify(testPapeData));
		fetch.subTestPaper(formData).then((data) => {
			if (data.result === 'RC100') {
			   message.success(data.errMsg, 3);
			   pub.jumpHistory.push('/NewsCenter')
               this.setState({
				point: data.answerScore,
				loading: false,
				removes:false
			  })
			} else {
				message.warning(data.errMsg, 3);
				pub.jumpHistory.push('/NewsCenter')
				this.setState({
					loading:false,
				})
			}
		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false,
			});
		})
	}
	clearTimer() {
		this.setState({
			end:true,
		})
		this.timer && clearTimeout(this.timer);
		clearInterval(this.timer);
	}

	render() {
		return(
		<div className="wrapper bg-F0F4F6">
			<div className="layout clearFix">
				{this.state.showTip?<div className="tip">Tips：若答题结果不理想，您可重新学习当前课程后再次答题，系统最终将记录您当前课程的最高答题得分。
				   <i className="icon-remove floatR" onClick={()=>{this.setState({showTip:false})}}></i>
				</div>:null}
				<div className="answer-time bg-FFFFFF">答题倒计时：<span>{this.state.hourAuction}:{this.state.minAuction}:{this.state.secAuction}</span></div>
	        </div>
	        <Spin spinning={this.state.loading} tip="加载列表中...">
	        <div className="panel-120 bg-FFFFFF box-shadow">
	          <RadioList single={this.state.single} />
	          <MultiselectList multiple={this.state.multiple} />
			  {this.state.removes===true?
				<div className="row submit-btn mar-b-20 mar-t-20 text-center">
				<button className="btn btn-blue" onClick={()=>this.submit()}>提交</button>
			    </div>:
				<div className="row submit-btn mar-b-20 mar-t-20 text-center">
				<button className="btn btn-blue" onClick={()=>{window.history.back();}}>返回</button>
			    </div>
				  }
				 
	        </div>
	        </Spin>

       <Layer 
         title = "答题成功"
         show={this.state.showLayer} 
         hide={()=>{this.setState({showLayer:false},()=>{pub.jumpHistory.push('/NewsCenter')})}}
         width="500px"
         height="280px"
       >
               <div className="row">
							<div className="pop-box-1">
								<div><i className="icon-ok-sign"></i></div>
						<h2>恭喜您，已经完成本次答题！</h2>
						<p>本次答题成绩为：<span>{this.state.point}</span>分</p>
					</div>
					<div className="pop-btn">
						<Link to="LearnCenter" className="btn btn-blue">学习中心</Link>
						<a className="btn btn-blue" onClick={()=>{window.history.back();}}>再次学习</a>
					</div>
				</div>

       </Layer>
       

	    </div>
			)
	}
}
export default TestPaper